package com.example.vw.tabletest.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.vw.tabletest.R;
import com.example.vw.tabletest.bean.ReportInfo;
import com.example.vw.tabletest.fragment.ExcelsPagerFragment;
import com.example.vw.tabletest.util.Constant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import static android.view.KeyEvent.KEYCODE_BACK;

public class TableTest extends AppCompatActivity implements ViewPager.OnPageChangeListener,ExcelsPagerFragment.ILoadWebView {

    private TabLayout mTab;
    private ViewPager mPager;
    private int mSelectedPos;//当前活动状态的表格界面下标
    private LinkedList<ExcelsPagerFragment> excelsPagerFragmentList;//表格fragment集合

    private String fcode = "510122106200001";//调查对象id
    private ArrayList<ReportInfo> mReportInfo;//所有表格对象的集合，包含表格id等信息
    /**
     * 所有表单控件的加载进度
     */
    private Map<Integer,Integer> mLoadProgresses = null;
    private ProgressDialog mLoadTabledialog;//加载表格时的进度框


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_test);

        //表格数据的准备，以及网页表格的绘制
        mLoadTabledialog = new ProgressDialog(this);
        mLoadTabledialog.setMessage("正在加载表单数据...");
        mLoadTabledialog.setIndeterminate(true);
        mLoadTabledialog.setCancelable(false);
        mLoadTabledialog.show();
        getParameters();
        initFragmentList();
        loadTabs();
    }

    /**
     * 获取调查对象信息
     */
    private void getParameters() {
        Intent sourceIntent = getIntent();
        // todo 建议此处的数据从前一个页面传入
        mReportInfo = new ArrayList<ReportInfo>();
        ReportInfo r1= new ReportInfo();
        r1.setText("调查表1");
        r1.setId("1538235454853");
        r1.setUrl("https://cn.bing.com/search?q=%E6%AD%BB%E7%A5%9E&qs=n&form=QBLH&sp=-1&pq=%E6%AD%BB%E7%A5%9E&sc=8-2&sk=&cvid=5A819FF69CE84CD49848F60DEE556EF");
        ReportInfo r2= new ReportInfo();
        r2.setText("调查表2");
        r2.setId("1538214427618");
        r2.setUrl("http://122.224.94.108:8005");
        ReportInfo r3= new ReportInfo();
        r3.setText("调查表3");
        r3.setId("1538214464419");
        r3.setUrl("http://211.103.218.91:8095");
        ReportInfo r4= new ReportInfo();
        r4.setText("调查表4");
        r4.setId("1539185488963");
        r4.setUrl(" http://211.103.218.91:8095/appdemo.html?table=1538214464419&catalogID=510122106200001&year=2018&period=4&userID=278_1 ");
        mReportInfo.add(r1);
        mReportInfo.add(r2);
        mReportInfo.add(r3);
        mReportInfo.add(r4);
    }

    /**
     * 初始化Fragment集合
     */
    private void initFragmentList() {

        excelsPagerFragmentList = new LinkedList<>();
        mLoadProgresses = new HashMap<Integer, Integer>();
        for (int i = 0; i < mReportInfo.size(); i++) {
            String reportId = mReportInfo.get(i).getId();
            Log.i("reportId", "reportId=" + reportId);
            String fileName = mReportInfo.get(i).getText();
            ExcelsPagerFragment fragment = new ExcelsPagerFragment();
            Bundle args = new Bundle();

            args.putInt(Constant.INDEX_TABEL,i);
            args.putString(Constant.KEY_ID, mReportInfo.get(i).getId());
            args.putString(Constant.KEY_PID, mReportInfo.get(i).getPid());
            args.putString(Constant.KEY_TEXT, mReportInfo.get(i).getText());
            args.putString(Constant.KEY_URL, mReportInfo.get(i).getUrl());
            args.putString(Constant.KEY_FCODE, fcode);

            fragment.setArguments(args);
            fragment.setOnLoadWebView(this);
            excelsPagerFragmentList.add(fragment);
        }
    }


    private void loadTabs(){
        mTab = (TabLayout) findViewById(R.id.tab);
        mPager = (ViewPager) findViewById(R.id.pager);
        CustomFragmentAdapter pagerAdapter = new CustomFragmentAdapter(getSupportFragmentManager());
        mPager.setAdapter(pagerAdapter);
        mPager.setOffscreenPageLimit(100);
        mPager.addOnPageChangeListener(this);
        mTab.setupWithViewPager(mPager, true);
        //修改tab
        for (int i = 0; i < mTab.getTabCount(); i++) {
            TabLayout.Tab tab = mTab.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(pagerAdapter.getTabView(i));
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mSelectedPos = position;
        String report_ID = mReportInfo.get(mSelectedPos).getId();

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onProgressChanged(int Index, int newProgress) {
        mLoadProgresses.put(Index,newProgress);
        if(!checkTableLoadProgress()) {
            this.setTitle("表单加载中……");
            this.setProgress(newProgress * 100);
        }else{
            this.setTitle(R.string.app_name);
            if (mLoadTabledialog.isShowing()) {
                mLoadTabledialog.dismiss();
            }
        }
    }

    /**
     * 检测表单加载进度
     */
    private boolean checkTableLoadProgress(){
        for(int progress :mLoadProgresses.values()){
            if(progress!=100)
                return false;
        }
        return true;
    }


    /**
     * 表格pager适配器
     */
    private class CustomFragmentAdapter extends FragmentPagerAdapter {

        CustomFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return excelsPagerFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return excelsPagerFragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mReportInfo.get(position).getText();
        }

        private View getTabView(int position) {
            View inflate = View.inflate(TableTest.this, R.layout.tab_custom_view, null);
            TextView textView = (TextView) inflate.findViewById(R.id.tv_tab_text);
            ImageView imageView = (ImageView) inflate.findViewById(R.id.iv_tab_state);
            textView.setText(getPageTitle(position));
            return inflate;
        }
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KEYCODE_BACK) && excelsPagerFragmentList.get(mSelectedPos).goBack()) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
